package com.basics.common.utils.http;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    public HttpUtils() {
    }

    public static String sendGet(String url, String param) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;

        try {
            String urlNameString = url + "?" + param;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;
            while((line = in.readLine()) != null) {
                result.append(line);
            }

            log.info("recv - {}", result);
        } catch (ConnectException var22) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, var22);
        } catch (SocketTimeoutException var23) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, var23);
        } catch (IOException var24) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, var24);
        } catch (Exception var25) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, var25);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception var21) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, var21);
            }

        }

        return result.toString();
    }

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();

        try {
            String urlNameString = url + "?" + param;
            log.info("sendPost - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

            String line;
            while((line = in.readLine()) != null) {
                result.append(line);
            }

            log.info("recv - {}", result);
        } catch (ConnectException var23) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, var23);
        } catch (SocketTimeoutException var24) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, var24);
        } catch (IOException var25) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, var25);
        } catch (Exception var26) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, var26);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var22) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, var22);
            }

        }

        return result.toString();
    }

    public static String sendSSLPost(String url, String param) {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;

        try {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init((KeyManager[])null, new TrustManager[]{new HttpUtils.TrustAnyTrustManager()}, new SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection)console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new HttpUtils.TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";

            while((ret = br.readLine()) != null) {
                if (ret != null && !ret.trim().equals("")) {
                    result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
                }
            }

            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        } catch (ConnectException var10) {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, var10);
        } catch (SocketTimeoutException var11) {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, var11);
        } catch (IOException var12) {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, var12);
        } catch (Exception var13) {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, var13);
        }

        return result.toString();
    }

    public static String sendPostMap(String url, Map<String, String> parameters) {
        String result = "";
        BufferedReader in = null;
        PrintWriter out = null;
        StringBuffer sb = new StringBuffer();
        String params = "";

        try {
            Iterator var7;
            String name;
            if (parameters.size() == 1) {
                var7 = parameters.keySet().iterator();

                while(var7.hasNext()) {
                    name = (String)var7.next();
                    sb.append(name).append("=").append(URLEncoder.encode((String)parameters.get(name), "UTF-8"));
                }

                params = sb.toString();
            } else if (parameters.size() > 0) {
                var7 = parameters.keySet().iterator();

                while(var7.hasNext()) {
                    name = (String)var7.next();
                    sb.append(name).append("=").append(URLEncoder.encode((String)parameters.get(name), "UTF-8")).append("&");
                }

                String temp_params = sb.toString();
                params = temp_params.substring(0, temp_params.length() - 1);
            }

            URL connURL = new URL(url);
            HttpURLConnection httpConn = (HttpURLConnection)connURL.openConnection();
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("Content-Type", "application/json");
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            out = new PrintWriter(httpConn.getOutputStream());
            out.write(params);
            out.flush();

            String line;
            for(in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8")); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var18) {
            var18.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var17) {
                var17.printStackTrace();
            }

        }

        return result;
    }

    public static String sendPost2(String url, String data) {
        String response = null;

        try {
            CloseableHttpClient httpclient = null;
            CloseableHttpResponse httpresponse = null;
            try {
                httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost(url);
                StringEntity stringentity = new StringEntity(data,
                        ContentType.create("application/json", "UTF-8"));

                httppost.setEntity(stringentity);
                httpresponse = httpclient.execute(httppost);
                response = EntityUtils
                        .toString(httpresponse.getEntity(),"UTF-8");

            } finally {
                if (httpclient != null) {
                    httpclient.close();
                }
                if (httpresponse != null) {
                    httpresponse.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    public static void main(String[] args) {
        Map<String, String> param = new HashMap();
        param.put("token", "13812341234");
        param.put("tradcoin", "ETC");
        param.put("type", "1");
        param.put("number", "100");
        JSONObject json = JSONObject.parseObject(sendPostMap("http://47.75.67.231/api/setconaccount", param));
        System.out.println(json.toJSONString());
        System.out.println(sendGet("http://47.75.67.231/api/getklines", "range=900000&symbol=ETH_USD&area=0"));
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        private TrustAnyHostnameVerifier() {
        }

        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static class TrustAnyTrustManager implements X509TrustManager {
        private TrustAnyTrustManager() {
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
}
